package org.dragonnova.meetingapp.app.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import org.dragonnova.meetingapp.R;
import org.dragonnova.meetingapp.app.adapter.DeviceAdapter;
import org.dragonnova.meetingapp.core.manager.UdpManager;
import org.dragonnova.meetingapp.model.bean.DeviceInfo;
import org.dragonnova.meetingapp.app.service.WIFIServiceTest;
import org.dragonnova.meetingapp.utils.Constants;
import org.dragonnova.meetingapp.utils.LogUtil;
import org.dragonnova.meetingapp.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

public class DeviceActivity extends AppCompatActivity implements ServiceConnection {

    private ListView mListView;
    private DeviceAdapter mAdapter;
    private List<DeviceInfo> deviceList = new ArrayList<>();//存放设备的list

    private WIFIServiceTest wifiService;//wifi服务
    private WIFIServiceTest.WifiBinder wifiBinder;
    private Button device_bt_search;

    private boolean isEditing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) getSupportActionBar().setDisplayShowTitleEnabled(false);

        TextView record_tb_tv_rename = (TextView) toolbar.findViewById(R.id.record_tb_tv_rename);
        record_tb_tv_rename.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isEditing = !isEditing;
                setEditable();

            }
        });

        mListView = (ListView) this.findViewById(R.id.device_lv);
        device_bt_search = (Button) this.findViewById(R.id.device_bt_search);

        device_bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (wifiBinder != null) {
                    wifiBinder.searchDevices();
                }
                ToastUtil.showTip("正在搜索设备....");
            }
        });

        //初始化聊天记录
        mAdapter = new DeviceAdapter(DeviceActivity.this, deviceList, this);
        mListView.setAdapter(mAdapter);

        /*mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                LayoutInflater inflater = LayoutInflater.from(DeviceActivity.this);
                final View textEntryView = inflater.inflate(
                        R.layout.dialog_rename, null);
                final EditText device_et_rename = (EditText) textEntryView.findViewById(R.id.device_et_rename);
                final AlertDialog.Builder builder = new AlertDialog.Builder(DeviceActivity.this);
                builder.setCancelable(false);
                builder.setTitle("请输入新的名称");
                builder.setView(textEntryView);
                builder.setPositiveButton("确认",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                String newName = device_et_rename.getText().toString();
                                try {
                                    DeviceInfo info = (DeviceInfo) deviceList.get(position).clone();
                                    info.setHostName(newName);
                                    wifiBinder.renameDevice(info);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                builder.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                            }
                        });
                builder.show();


            }
        });*/

        bindService();
        registerBroadcastReceiver();
    }

    public void setName(int position, String name) {
        isEditing = false;
        setEditable();
        try {
            DeviceInfo info = (DeviceInfo) deviceList.get(position).clone();
            info.setHostName(name);
            wifiBinder.renameDevice(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setEditable() {
        if (isEditing) {
            ToastUtil.showTip("启动修改");
            device_bt_search.setVisibility(View.GONE);
        } else {
            ToastUtil.showTip("关闭修改");
            device_bt_search.setVisibility(View.VISIBLE);
            View v = getCurrentFocus();
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

        }
        mAdapter.setIsEditable(isEditing);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindService();
        unRegisterBroadcastReceiver();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * 绑定服务
     */
    private void bindService() {
        //启动服务
        Intent wifiIntent = new Intent(DeviceActivity.this, WIFIServiceTest.class);
        bindService(wifiIntent, this, BIND_AUTO_CREATE);
    }

    /**
     * 解除服务绑定
     */
    private void unbindService() {
        unbindService(this);
        LogUtil.eee("unbind service successfully");
    }

    /**
     * 注册广播
     */
    private void registerBroadcastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.WIFI_BORADCAST_ACTION);
        registerReceiver(WifiReceiver, filter);
    }

    private void unRegisterBroadcastReceiver() {
        unregisterReceiver(WifiReceiver);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (service instanceof WIFIServiceTest.WifiBinder) {
            wifiBinder = (WIFIServiceTest.WifiBinder) service;
            wifiService = ((WIFIServiceTest.WifiBinder) service).getService();
            device_bt_search.performClick();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    /**
     * wifi service发送的广播
     */
    private BroadcastReceiver WifiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.WIFI_BORADCAST_ACTION)) {
                String option = intent.getStringExtra(Constants.BORADCAST_INTENT_OPTION);
                switch (option) {
                    case UdpManager.KEY_HANDLER_DEVICE_INFO:
                        Bundle bundle = intent.getExtras();
                        if (bundle.getSerializable("DevicesInfos") instanceof List) {
                            List devicesInfos = (List) bundle.getSerializable("DevicesInfos");
                            deviceList.clear();
                            if (devicesInfos != null) {
                                deviceList.addAll(devicesInfos);
                                mAdapter.notifyDataSetChanged();
                                mListView.setSelection(mAdapter.getCount() - 1);
                            }
                        }
                        break;
                }
            }
        }
    };
}
